import { asyncRoutes, constantRoutes } from '@/router'
import { getRoutes } from '@/api/user'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// eslint-disable-next-line no-unused-vars
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// 这里选择使用后端传过来的有权限的route的path 过滤
function hasPermission0(roles, route, menus) {
  // console.log(route)
  return menus.includes(route.path) || route.path === '*'
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 * @param menus
 */
export function filterAsyncRoutes(routes, roles, menus) {
  // console.log(menus)
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission0(roles, tmp, menus)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles, menus)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 注意所有路由的path一定要不一样，不然这样控制权限就有问题
  generateRoutes({ commit }, data) {
    const { roles, menus } = data
    // console.log(data)
    return new Promise(resolve => {
      let accessedRoutes
      // eslint-disable-next-line prefer-const
      // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles, menus)
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles, menus)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
